//
// Created by 神秘悟饭 on 2020/7/7.
//
#include "dose_adjust.h"
#include "iostream"
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>

using namespace cv;

int dose_adjust(Mat image , int &kv, int &autoKvType, int &partType)
{
    int meanLow = 0,meanHigh = 1,stdLow = 2,stdHigh = 3;
    int newKv;
    Mat mean,std;
    Mat M ; // 存放mean和std的上下限
    // 1颈椎，2脊椎，3胸椎，4髋部，5四肢
    Mat m1 = (Mat_<float>(1, 4) << 20000,22000,18000,20000);
    Mat m2 = (Mat_<float>(1, 4) << 20000,22000,18000,20000);
    Mat m3 = (Mat_<float>(1, 4) << 20000,22000,18000,20000);
    Mat m4 = (Mat_<float>(1, 4) << 20000,22000,18000,20000);
    Mat m5 = (Mat_<float>(1, 4) << 20000,22000,18000,20000);
    M.push_back(m1);
    M.push_back(m2);
    M.push_back(m3);
    M.push_back(m4);
    M.push_back(m5);

    meanStdDev(image,mean,std);
    double m = mean.at<double>(0,0);
    double s = std.at<double>(0,0);
//    std::cout << "Mean: " << m << " , StdDev: " << s << '\n';

    switch(autoKvType)
    {
        case 0:// 不调整
            newKv = kv;
            break;
        // 标准模式既考虑方差，又考虑均值
        case 1:
            if ((s < M.at<double>(partType,meanLow)) || (s < M.at<double>(partType,stdLow)))
            {
                newKv = (kv+100)/2;
            }
            else if ((s > M.at<double>(partType,meanHigh)) || (s > M.at<double>(partType,stdHigh)))
            {
                newKv = (kv+60)/2;
            }
            else
            {
                newKv = kv;
            }
            break;
        case 2: //低剂量模式，不考虑曝光，也就是不考虑均值，只考虑方差，定义低剂量的电压范围   kv = 40:100
            if (s < M.at<double>(partType,stdLow))
            {
                newKv = (kv+100)/2;
            }
            else if (s > M.at<double>(partType,stdHigh))
            {
                newKv = (kv+40)/2;
            }
            else
            {
                newKv = kv;
            }
            break;
        // 考虑曝光，均值是重要因素，高剂量模式，达到均值的下阈值，对比度就在可以接受的范围内了，即（方差）不是十分重要的指标
        // 高剂量模式 此时优先保证图像质量，图像必须很好，剂量稍微大一点没有关系 kv = 70:120
        case 3:

            if (s < M.at<double>(partType,meanLow))
            {
                newKv = (kv+120)/2;
            }
            else if (s > M.at<double>(partType,meanHigh))
            {
                newKv = (kv+70)/2;
            }
            else
            {
                newKv = kv;
            }
            break;


    }
    return newKv;
}
